<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 张兵 <>
// +----------------------------------------------------------------------
error_reporting(E_ERROR | ~E_NOTICE);
/**
 * @param $list
 * @param int $parent_id
 * @param int $deep
 * @return array
 * 递归获取权限
 */
function infinite($list = [],$parent_id = 0,$deep = 0){
    static $arr = [];
    foreach ($list as $v){
        if($v['p_id'] == $parent_id){
            $v['deep'] = $deep;
            $arr[] = $v;
            infinite($list,$v['id'],$deep + 1);
        }
    }
    return $arr;
}

/**
 * 多图上传
 * @param $fileName 上传文件名
 * @return mixed
 * @throws Exception
 */
function upload($fileName){
    // 获取表单上传文件
    $files = request()->file('image');
    foreach($files as $file){
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->validate(['size'=>2097152,'ext'=>'jpg,png,gif'])->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $fileName);
        if(false === $info){
            // 上传失败获取错误信息
            throw new \LogicException($file->getError(),1022);
        } else {
            $thumb = \think\Image::open($info->getPathName());
            // 按照原图的比例生成一个最大为150*150的缩略图,居中剪裁并保存
            $thumb->thumb(250, 250,\think\Image::THUMB_CENTER)->save(ROOT_PATH . 'public' . DS . 'uploads' . DS . $fileName. DS .'s'.$info->getSaveName());
            // 成功上传后 获取上传信息
            $filePath[]   = $info->getSaveName();
        }
    }
    return $filePath;
}

/**
 * 多图上传
 * @param $fileName 上传文件名
 * @return mixed
 * @throws Exception
 */
function uploadVideo($fileName){
    // 获取表单上传文件
    $file = request()->file('file');
    $path = $file->move(ROOT_PATH . 'public' . DS . 'uploads'. DS . $fileName );
    if(!$path) die('视频上传失败');
    return date('Ymd').DS.$path->getFilename();
}

/**
 * 搜索调用
 * @param array $data 查询条件
 * @param string $time 时间字段名
 * @param string $name 名称字段名,多个字段用逗号隔开
 * @param string $status 状态
 * @return array
 * */
function search($data,$name = '',$time = '',$status = ''){
    $condition = 1;
    $display   = array();
    // 根据时间查询
    if(!empty($data['startTime'])){
        $startTime  = strtotime($data['startTime']);
        $condition .= " and $time > {$startTime}";
        $display['startTime'] = $data['startTime'];
    }
    if(!empty($data['endTime'])){
        $endTime    = strtotime(date('Y-m-d',strtotime($data['endTime'].'+1 day')));
        $condition .= " and $time < {$endTime}";
        $display['endTime'] = $data['endTime'];
    }
    if(!empty($data['startTime']) && !empty($data['endTime'])){
        $startTime  = strtotime($data['startTime']);
        $endTime    = strtotime(date('Y-m-d',strtotime($data['endTime'].'+1 day'))) - 1;
        $condition .= " and $time between {$startTime} and {$endTime}";
        $display['startTime'] = $data['startTime'];
        $display['endTime']   = $data['endTime'];
    }
    // 根据名称查询
    if(!empty($data['searchName'])){
        $arr = explode(',',$name);
        $condition .= ' and ( 0';
        foreach($arr as $v){
            $condition .= " or $v like '%{$data['searchName']}%'";
        }
        $condition .= ')';
        $display['searchName'] = $data['searchName'];
    }
    // 根据状态查询
    if($data['status'] != ''){
        $condition .= " and $status = {$data['status']}";
        $display['status'] = $data['status'];
    }
    return array('condition' => $condition,'display' => $display);
}

/**
 * 输出时间
 * @param $time
 * @return string
 */
function formatDate($time){
    $difference = time()-$time;
    $date_arr = [
        '31536000'=>'年',
        '2592000'=>'个月',
        '604800'=>'星期',
        '86400'=>'天',
        '3600'=>'小时',
        '60'=>'分钟',
        '1'=>'秒'];
    foreach ($date_arr as $k=>$v){
        if(0 != $c = floor($difference/(int)$k)){
            return $c.$v.'前';
        }
    }
}

/**
 * 根据两点间的经纬度计算距离
 * @param $lat1
 * @param $lng1
 * @param $lat2
 * @param $lng2
 * @return float
 */
function getDistance($lng1, $lat1, $lng2, $lat2){
    $earthRadius = 6367000; //approximate radius of earth in meters
    $lat1 = ($lat1 * pi() ) / 180;
    $lng1 = ($lng1 * pi() ) / 180;
    $lat2 = ($lat2 * pi() ) / 180;
    $lng2 = ($lng2 * pi() ) / 180;
    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;
    return round($calculatedDistance);
}

/**
 * 根据生日获取年龄和星座
 * @param $birthday
 * @return int|string
 */
function calcAge($birthday) {
    $age = 0;
    $signs = array( array('20' => '水瓶座'), array('19' => '双鱼座'), array('21' => '白羊座'), array('20' => '金牛座'), array('21' => '双子座'), array('22' => '巨蟹座'), array('23' => '狮子座'), array('23' => '处女座'), array('23' => '天秤座'), array('24' => '天蝎座'), array('22' => '射手座'), array('22' => '摩羯座'));
    if (!empty($birthday)) {
        $age = strtotime($birthday);
        if ($age === false) {
            return 0;
        }
        list($y1, $m1, $d1) = explode("-", date("Y-m-d", $age));
        list($y2, $m2, $d2) = explode("-", date("Y-m-d"), time());
        $age = $y2 - $y1;
        //下面是判断月份大小，如果只是逄年份的可以去掉，如果算上月份的话，比如：2000年4月1日，那算出来是16算，要到了4月，算出来才是17岁
        if ((int)($m2 . $d2) < (int)($m1 . $d1)) {
            $age -= 1;
        }

        //星座
        $key = (int)$m1 - 1;
        list($startSign, $signName) = each($signs[$key]);
        if ($d1 < $startSign) {
            $key = $m1 - 2 < 0 ? $m1 = 11 : $m1 -= 2;
            list($startSign, $signName) = each($signs[$key]);
        }
    }
    //return ['age'=>$age,'zodiac_sign'=>$signName];
    return $age;
}

/**
 * 生成订单号
 * @return string
 */
function getOrderNo(){
    return date('YmdHis').rand(0001,9999);
}

/**
 * Curl请求
 *
 * @param string $requesturl //请求URL
 * @param string $reuqestmothed //请求方法 默认false（为GET） true（为POST）
 * @param int $httpcode http状态码 以引用的形式传递
 * @param int $postdata post的数据
 * @return string or false
 */
function curlRequest($requesturl,$reuqestmethod=false,& $httpcode=0,$postdata=NULL) {
    try {
        $options = array(
            CURLOPT_URL => $requesturl,
            CURLOPT_RETURNTRANSFER  => true,  //启用回去返回数据
            CURLOPT_FOLLOWLOCATION => true,   // follow redirects
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_POST => $reuqestmethod
        );
        if(true === $reuqestmethod){
            $options[CURLOPT_POSTFIELDS] = $postdata;
        }
        $ch = curl_init();//初始化
        curl_setopt_array($ch,$options);//参数设置
        $rs = curl_exec($ch);//执行s
        $httpcode =curl_getinfo($ch,CURLINFO_HTTP_CODE); //http状态码
        curl_close($ch);
        unset($ch);
        return $rs;
    }catch (\Exception $ex){
        throw $ex;
    }
}

/**
 * 抓接口
 * @return mixed
 */
function curl(){
    $url = "https://rili.jin10.com/datas/2017/0807/economics.json";
    $queryServer = curl_init();
    curl_setopt($queryServer, CURLOPT_URL, $url);
    curl_setopt($queryServer, CURLOPT_HEADER, 0);
    curl_setopt($queryServer, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($queryServer, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($queryServer, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($queryServer, CURLOPT_TIMEOUT, 30);
    $data = curl_exec($queryServer);
    //$data = iconv('UTF-8','GBK//IGNORE',$html); // 转GBK
    return $data;
}

/**
 * 获取本周第一天开始和最后一天结束时间
 * @return array
 */
function week(){
    //当前日期
    $today = date("Y-m-d");
    //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
    $first = 1;
    //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
    $w = date('w',strtotime($today));
    //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
    $week_start = date('Y-m-d',strtotime("$today -".($w ? $w - $first : 6).' days'));
    //本周结束日期
    $week_end = date('Y-m-d',strtotime("$week_start +7 days"));
    $week_start = strtotime($week_start);
    $week_end   = strtotime($week_end) - 1;
    return ['w_start'=>$week_start,'w_end'=>$week_end];
}

/**
 * 获取本月开始和结束时间
 * @return array
 * mktime(hour,minute,second,month,day,year);
 */
function month(){
    $m = date('Y-m-d', mktime(0,0,0,date('m'),1,date('Y'))); // 本月的开始日期
    $t = date('t',strtotime($m)); // 本个月共多少天
    $start = date('Y-m-d', mktime(0,0,0,date('m'),1,date('Y'))); // 本月的开始日期
    $end   = date('Y-m-d', mktime(0,0,0,date('m'),$t+1,date('Y'))); // 本月的结束日期
    $m_start = strtotime($start);
    $m_end   = strtotime($end) - 1;
    return ['m_start'=>$m_start,'m_end'=>$m_end];
}

